package com.cbl.v.ssczs.view.activity;

import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.http.SslError;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cbl.v.ssczs.R;
import com.cbl.v.ssczs.mode.util.DialogUtils;
import com.cbl.v.ssczs.mode.util.NetStatusUtil;
import com.cbl.v.ssczs.view.agent.OnPageListener;
import com.mingle.widget.ShapeLoadingDialog;

/**
 * 时时彩宝典 时时彩走势至尊版
 */
public class AGActivity extends com.cbl.v.ssczs.view.activity.BaseActivity {
    private WebView mWebView;
    private TextView mBtnShare;
    OnPageListener onPageListener;
    private ImageView title_back;
    private String webUrl;
    private SwipeRefreshLayout mSwipeRefresh;
    private LinearLayout mNoNetLayout;
    private ShapeLoadingDialog shapeLoadingDialog;

    @Override
    protected int getLayout() {
        return R.layout.activity_webview;
    }

    @Override
    public void initView() {
        shapeLoadingDialog = new ShapeLoadingDialog(AGActivity.this);
        initToolBar();
        mBtnShare = (TextView) findViewById(R.id.btn_share);
        hideTitleBar();
        mWebView = (WebView) findViewById(R.id.web);
        initWebView(mWebView);
        //        webUrl = "https://video.1398t.com/pk10/h5shipin/?app=1";
        //        webUrl = "https://m.qmcai.com/hd/caipiaoclass/index.html";
        //        webUrl = "https://m.qmcai.com/zixun/index.html";
        webUrl = "https://m.qmcai.com/hd/caipiaoclass/index" +
                ".html?fromType=cpkt_k3&hideTab=true&isTouzhu=false&newWebview=true&backH5Control=true" +
                "&h5ControlTitle=true&version=5.2.16&channel=980";
        mWebView.loadUrl(webUrl);

        initRefresh();
    }

    private void initToolBar() {
        Toolbar toolBar = (Toolbar) findViewById(R.id.toolbar);
        toolBar.setBackground(getResources().getDrawable(R.color.bg_red));
        TextView title_name = (TextView) findViewById(R.id.title_name);
        title_back = (ImageView) findViewById(R.id.title_back);
        title_back.setVisibility(View.VISIBLE);
        title_name.setText("");
        setSupportActionBar(toolBar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setDisplayShowTitleEnabled(false);
        }
        toolBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mWebView.canGoBack()&&!mWebView.getUrl().equals(webUrl)) {
                    mWebView.goBack();
                } else {
                    finish();
                }
            }
        });
        toolBar.setTitle("上海快三投注技巧");
        toolBar.setTitleTextColor(Color.WHITE);
    }

    private void initRefresh() {
        mNoNetLayout = (LinearLayout) findViewById(R.id.linearLayout_no_net);
        if (!NetStatusUtil.isConnected(this)) {
            mNoNetLayout.setVisibility(View.VISIBLE);
        } else {
            mNoNetLayout.setVisibility(View.GONE);
        }
        mSwipeRefresh = (SwipeRefreshLayout) findViewById(R.id.swipeRefresh);
        //设置刷新时动画的颜色，可以设置4个
        mSwipeRefresh.setColorSchemeResources(android.R.color.holo_blue_light, android.R.color.holo_red_light,
                android.R.color.holo_orange_light, android.R.color.holo_green_light);
        mSwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (!NetStatusUtil.isConnected(getContext())) {
                                    mNoNetLayout.setVisibility(View.VISIBLE);
                                    Toast.makeText(getContext(), "无网络", Toast.LENGTH_SHORT).show();
                                } else {
                                    mNoNetLayout.setVisibility(View.GONE);
                                    mWebView.reload();
                                }

                                mSwipeRefresh.setRefreshing(false);
                            }
                        });
                    }
                }).start();
            }
        });
    }

    @Override
    public void initData() {
        setOnPageListener(new OnPageListener() {
            @Override
            public void onStart() {
                if (!NetStatusUtil.isConnected(getContext())) {
                    DialogUtils.showErrorWithStatus("无网络 0_0", AGActivity.this);
                    Toast.makeText(AGActivity.this, "请检查网络！", Toast.LENGTH_SHORT);
                }
            }

            @Override
            public void onFinish() {
                shapeLoadingDialog.dismiss();
                if (!NetStatusUtil.isConnected(getContext())) {
                    DialogUtils.showErrorWithStatus("无网络 0_0", AGActivity.this);
                    Toast.makeText(AGActivity.this, "请检查网络！", Toast.LENGTH_SHORT);
                }
            }

            @Override
            public void onError() {
                if (!NetStatusUtil.isConnected(getContext())) {
                    shapeLoadingDialog.dismiss();
                    mNoNetLayout.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    @Override
    public void initListener() {

    }

    public void initWebView(WebView mWebView) {
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.getSettings().setSupportMultipleWindows(true);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setSavePassword(false);
        mWebView.setVerticalScrollBarEnabled(false);
        mWebView.setHorizontalScrollBarEnabled(false);
        mWebView.getSettings().setSupportZoom(true);
        mWebView.getSettings().setUseWideViewPort(true);
        mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        mWebView.getSettings().setLoadWithOverviewMode(true);
        mWebView.setWebChromeClient(new WebChromeClient());
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url == null) return false;

                try {
                    if (url.startsWith("qmcai://")) {
                        if (url.endsWith("jczdg") ||
                                url.endsWith("bjdc") ||
                                url.endsWith("jcz") ||
                                url.endsWith("BasketBallActivity")) {
                            Toast.makeText(AGActivity.this, "　　请严格遵守法律法规！\n" +
                                    "请到附近的实体店以现金购买！\n" +
                                    "谢谢您的支持！祝您好运哦 ！", Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(AGActivity.this, "此功能将在下一个版本开放！", Toast.LENGTH_SHORT).show();
                        }

                        //                        Intent intent = new Intent(AGActivity.this,BallActivity.class);
                        ////                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www
                        /// .jianshu.com/p/5fa942d26628"));
                        //                        startActivity(intent);
                        return true;
                    }
                } catch (Exception e) { //防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
                    return true;//没有安装该app时，返回true，表示拦截自定义链接，但不跳转，避免弹出上面的错误页面
                }


                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                onPageListener.onStart();
                shapeLoadingDialog.setLoadingText("加载中...");
                shapeLoadingDialog.show();
                onPageListener.onError();
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                onPageListener.onFinish();
                if (!NetStatusUtil.isConnected(getContext())) {
                    mNoNetLayout.setVisibility(View.VISIBLE);
                } else {
                    mNoNetLayout.setVisibility(View.GONE);
                }

            }

            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                super.onReceivedHttpError(view, request, errorResponse);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode,
                                        String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                onPageListener.onError();
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }
        });
    }

    public void setOnPageListener(OnPageListener onPageListener) {
        this.onPageListener = onPageListener;
    }

    private long lastBackPress;

    @Override
    public void onBackPressed() {
        if (mWebView.canGoBack()) {
            if (mWebView.getUrl().equals(webUrl)) {
                super.onBackPressed();
            } else {
                mWebView.goBack();
            }
        } else {
            finish();
            //            if (System.currentTimeMillis() - lastBackPress < 1000) {
            //                ActivityGroup.finishAllActivity();
            //                android.os.Process.killProcess(android.os.Process.myPid());
            //                super.onBackPressed();
            //            } else {
            //                lastBackPress = System.currentTimeMillis();
            //                Toast.makeText(AGActivity.this, "再按一次退出", Toast.LENGTH_SHORT).show();
            //            }
        }
    }

    @Override
    protected void onDestroy() {
        if (mWebView != null) {
            mWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            mWebView.clearHistory();
            mWebView.removeAllViews();
            mWebView.destroy();
            mWebView = null;
        }
        super.onDestroy();
    }
}
